package top.chukongxiang.monitorservice.config;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
import top.chukongxiang.monitorservice.components.SockjsPrincipal;

import java.util.List;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/11/3 14:22
 */
@Slf4j
@Configuration
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {


    public static final String SOCK_JS_PREFIX = "/websocket";

    private static final String USER_DEST_PREFIX = "/user";

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint(SOCK_JS_PREFIX)
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // topic 定义为广播消息前缀
        // queue 定义为点对点消息前缀
        registry.enableSimpleBroker("/topic",  "/queue");
        // 客户端接收点对点消息前缀
        registry.setUserDestinationPrefix(USER_DEST_PREFIX);
        // 客户端向服务端发送消息前缀
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new AuthUserInterceptor());
    }

    /**
     * 客户端上线
     * @param sessionConnectedEvent
     */
    @EventListener
    public void socketConnectListener(SessionConnectedEvent sessionConnectedEvent) {
        String sessionId = (String) sessionConnectedEvent.getMessage().getHeaders().get("simpSessionId");
        log.info("[WebSocket] 客户端上线:{}", sessionId);
    }

    /**
     * 客户端离线
     * @param sessionDisconnectedEvent
     */
    @EventListener
    public void socketDisConnectListener(SessionDisconnectEvent sessionDisconnectedEvent) {
        MessageHeaders headers = sessionDisconnectedEvent.getMessage().getHeaders();
        String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
        log.info("[WebSocket] 客户端离线:{}", sessionId);
    }

    @EventListener
    public void subscribeListener(SessionSubscribeEvent sessionSubscribeEvent) {
        MessageHeaders headers = sessionSubscribeEvent.getMessage().getHeaders();
        String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
        String destination = SimpMessageHeaderAccessor.getDestination(headers);
        log.info("[WebSocket] {} 订阅: {}", sessionId, destination);
    }

    /**
     * 为消息请求添加 用户session
     */
    public static class AuthUserInterceptor implements ChannelInterceptor {
        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            SimpMessageHeaderAccessor simpMessageHeaderAccessor = SimpMessageHeaderAccessor.wrap(message);
            String sessionId = simpMessageHeaderAccessor.getSessionId();
            StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(message);
            StompCommand command = stompHeaderAccessor.getCommand();
            if (command == null) {
                return message;
            }
            switch (command) {
                case CONNECT: {
                    // 连接消息
                    List<String> name = simpMessageHeaderAccessor.getNativeHeader("name");
                    if (CollUtil.isNotEmpty(name)) {
                        String id = CollUtil.getFirst(name);
                        //设置当前访问器的认证用户
                        SockjsPrincipal sockjsPrincipal = new SockjsPrincipal(id);
                        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                        if (accessor != null) {
                            accessor.setUser(sockjsPrincipal);
                            SockJsContextHolder.addClient(sessionId, sockjsPrincipal);
                        }
                    }
                    break;
                }
                case DISCONNECT: {
                    // 断开连接消息
                    SockjsPrincipal principal = SockJsContextHolder.getClientId(sessionId);
                    //  如果同时发生两个连接，只有都断开才能叫做不在线
                    if (principal != null) {
                        SockJsContextHolder.remove(sessionId);
                    }
                    break;
                }
                default: {
                    //
                    break;
                }
            }
            return message;
        }
    }

}
